import fs from "fs";
import Spinnies from "spinnies";

const spinnies = new Spinnies();

const inputFileDir = "src/icons";
const outputFileDir = "src/assets/icons";

readdir(inputFileDir);

// 读取指定目录下的所有文件
function readdir(path: string) {
  fs.readdir(path, async (err, files) => {
    if (err) {
      console.error("Error", err);
      return;
    }
    deleteFolder(outputFileDir);
    fs.mkdirSync(outputFileDir, { recursive: true });
    spinnies.add("file", { text: "svg build..." });

    const results = files.map(async file => {
      const content = await readfile(`${path}/${file}`);
      const result = await writefile(`${outputFileDir}/${file}`, content.data, file);
      return result;
    });

    // 所有都写入完成输出打印信息
    Promise.all(results)
      .then(res => {
        const str = `export default [${res}]`;
        fs.writeFile(`${outputFileDir}/index.ts`, str, error => {
          if (error) {
            console.error("Error", error);
          }
        });
        spinnies.succeed("file", { text: `✨ svg create success in ${outputFileDir}` });
      })
      .catch(errs => {
        spinnies.fail("file", { text: errs });
      });
  });
}

// 写入文件
function writefile(path: string, data: string, file: string): Promise<string> {
  return new Promise((resolve, reject) => {
    fs.writeFile(path, data, errs => {
      if (errs) reject(errs);
      resolve(`"${file}"`);
    });
  });
}

// 读取单个文件
function readfile(path: string): Promise<{ path: string; data: string }> {
  return new Promise((resolve, reject) => {
    fs.readFile(path, "utf8", (err, data) => {
      if (err) reject(err);
      // 正则替换全局fill="***" 除了fill="white"
      data = data.replace(/fill="(?!white).*?"/g, "");
      resolve({ path, data });
    });
  });
}

// 递归删除文件
function deleteFolder(filePath: string) {
  if (fs.existsSync(filePath)) {
    const files = fs.readdirSync(filePath);
    files.forEach(file => {
      const nextFilePath = `${filePath}/${file}`;
      const stats = fs.statSync(nextFilePath);
      if (stats.isDirectory()) {
        deleteFolder(nextFilePath);
      } else {
        fs.unlinkSync(nextFilePath);
      }
    });
    fs.rmdirSync(filePath);
  }
}
